package com.tio.helloworldclient.client;

import cn.hutool.core.util.StrUtil;
import com.tio.helloworldclient.client.handler.HelloClientAioHandler;
import com.tio.helloworldclient.common.Constant;
import com.tio.helloworldclient.common.HelloPacket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.TioClient;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Node;
import org.tio.core.Tio;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.UnsupportedEncodingException;


/**
 *
 * @author tanyaowu
 *
 */
@Component
@Slf4j
public class HelloClientStarter {
	/**
	 * 服务器节点
	 */
	public static Node serverNode;

	public static TioClient tioClient = null;
	public static ClientChannelContext clientChannelContext = null;

	/**
	 * handler, 包括编码、解码、消息处理
	 */
	public static ClientAioHandler tioClientHandler = new HelloClientAioHandler();

	/**
	 * 事件监听器，可以为null，但建议自己实现该接口，可以参考showcase了解些接口
	 */
	public static ClientAioListener aioListener = null;

	/**
	 * 断链后自动连接的，不想自动连接请设为null
	 */
	private static ReconnConf reconnConf = new ReconnConf(5000L);

	/**
	 * 一组连接共用的上下文对象
	 */
	public static ClientGroupContext clientGroupContext = new ClientGroupContext(tioClientHandler, aioListener, reconnConf);


	/**
	 * 有时候需要绑定ip，不需要则null
	 */
	@Value("${tio.server.host}")
	private String serverIp;

	/**
	 * 监听的端口
	 */
	@Value("${tio.server.port}")
	private Integer serverPort;

	/**
	 * 启动Client
	 *
	 * @throws InterruptedException
	 */
	@PostConstruct
	public void start() throws Exception {
		serverNode = new Node(serverIp, serverPort);
		clientGroupContext.setHeartbeatTimeout(Constant.TIMEOUT);
		tioClient = new TioClient(clientGroupContext);
		clientChannelContext = tioClient.connect(serverNode);
		//连上后，发条消息玩玩
		HelloClientStarter.send("hello world");
	}

	@PreDestroy
	public void destory() {

	}


	public static void send(String msg)  {
		if(StrUtil.isBlank(msg)){
			return;
		}
		try {
			HelloPacket packet = new HelloPacket();
			packet.setBody(msg.getBytes(HelloPacket.CHARSET));
			Tio.send(clientChannelContext, packet);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
}
